package controller;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import server.ClientState;
import server.IProtocolHandler;
import xml.Message;

/**
 * This controller handles the use case where the administrator logs into the system.
 * Upon success, the response will include the key that the client should use for
 * all subsequent administrator-related requests. On failure, the response will indicate
 * the attempt was not successful and will contain 'Invalid credentials' as the reason.
 * 
 * @author Billy Hawkins
 *
 */
public class AdminLoginController implements IProtocolHandler {

	@Override
	public Message process(ClientState state, Message request) {
		
		// Get handle to the system
		entity.System system = entity.System.getInstance();
		
		// Extract the user name and password
		Node adminRequest = request.contents.getFirstChild();
		Node user = adminRequest.getChildNodes().item(0);
		NamedNodeMap attributeMap = user.getAttributes();
		String name  = attributeMap.getNamedItem("name").getNodeValue();
		String password  = attributeMap.getNamedItem("password").getNodeValue();
		
		// If successful, generate a key and return the response
		if (system.validateAdmin(name, password)) {
			String key = system.generateNewAdminKey();
			String response = Message.responseHeader(request.id());
			response += "<adminResponse key='" + key + "' /></response>";
			return new Message(response);
		}
		
		// Otherwise, return the response with an error message
		String response = Message.responseHeader(request.id(), "Invalid credentials");
		response += "<adminResponse key='' /></response>";
		return new Message(response);
	}

}

/*
<!-- AdminRequest           -->
<!-- ______________________ -->

<xs:element name='adminRequest'> 
  <xs:complexType>
    <!-- participant signs in with the following user/password -->
    <xs:sequence>
      <xs:element ref='user' minOccurs='1' maxOccurs='1'/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<!-- admin response returns key to be used for all future invocations -->
<xs:element name='adminResponse'>
  <xs:complexType>
    <xs:attribute name='key'   type='xs:string' use='required'/>
  </xs:complexType>
</xs:element>
*/